var express = require('express');
var router = express.Router();
/// 引入数据库模块
var _db = require('../mysql.js');
/// 引入全局变量模块
var other = require('../other.js');
var fs=require('fs');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('login', { title: 'Express' });
});

/// 用户登录
router.post('/userLogin', function (req, res, next) {
  /// 获取到用户输入的内容
  var val = req.body;
  var id = val.Username;
  var pwd = val.Password;
  _db.query('select * from students where StuNum=? and PassWord=?', [id, pwd], function (err, result) {
    if (err) {
      throw err;
      return;
    } else {
      if (result.length > 0) {
        /// 获取用户名字和学号并输入到全局变量中
        other._username = result[0].StuName;
        other._usernum = result[0].StuNum;
        /// 暴露名字信息 方便userinfo调用
        module.exports = other._username;
        /// 跳转根目录
        res.redirect('/');
        
        /// 渲染index界面
        /// res.render('index');
      }
      else {
        res.write('<head><meta charset="utf-8"/><style>body{text-align: center;margin-top: 50vh;}</style></head>');
        res.end('<span style="font-size: 50px;">用户名或密码有误！</span><br /><span style="">2秒钟后自动返回。。。</span><script src="https://code.jquery.com/jquery-3.7.0.js"></script><script>setTimeout(function(){window.location.assign(\'../login\');}, 2500);</script>');
      }
    }


  })

  // res.render('main', { title: 'Express' });
});

/// 管理员登录
router.post('/adminLogin', function (req, res, next) {
  /// 获取到用户输入的内容
  var val = req.body;
  var id = val.Username;
  var pwd = val.Password;
  _db.query('select * from admin where AdminName=? and AdminPassword=?', [id, pwd], function (err, result) {
    if (err) {
      throw err;
      return;
    } else {
      if (result.length > 0) {
        /// 获取用户名字和学号并输入到全局变量中
        other._adminname = result[0].AdminName;
        /// 跳转根目录
        res.redirect('/management');
        
        /// 渲染index界面
        /// res.render('index');
      }
      else {
        res.write('<head><meta charset="utf-8"/><style>body{text-align: center;margin-top: 50vh;}</style></head>');
        res.end('<span style="font-size: 50px;">用户名或密码有误！</span><br /><span style="">2秒钟后自动返回。。。</span><script src="https://code.jquery.com/jquery-3.7.0.js"></script><script>setTimeout(function(){window.location.assign(\'../login\');}, 2500);</script>');
      }
    }


  })

  // res.render('main', { title: 'Express' });
});

module.exports = router;
